import tank from '../canvas/tank'

import { DirectionEnum } from '../enum/directionEnum'
import { image, ImageMapKey } from '../service/image'
import util from '../util'
import ModelAbstract from './modelAbstract'

export default class TankModel extends ModelAbstract implements IModel {
  canvas: ICanvas = tank
  name: string = 'tank'

  image() {
    const tankDirection = (this.name + this.direction) as ImageMapKey

    return image.get(tankDirection)!
  }

  render(): void {
    this.move()
    // 增加坦克往下的几率
    if (Math.floor(Math.random() * 5) === 1) {
      this.direction = DirectionEnum.Bottom
    }
  }

  protected move(): void {
    const moveSpeed = 0.4
    while (true) {
      let x = this.x
      let y = this.y
      switch (this.direction) {
        case DirectionEnum.Top:
          y -= moveSpeed
          break

        case DirectionEnum.Right:
          x += moveSpeed
          break

        case DirectionEnum.Bottom:
          y += moveSpeed
          break

        case DirectionEnum.Left:
          x -= moveSpeed
          break
      }

      if (util.isModelTouch(x, y) || util.isCanvasTouch(x, y)) {
        this.randomDirection()
      } else {
        this.x = x
        this.y = y
        break
      }
    }
    super.draw()
  }
}
